package xin.marcher.module.common.utils.diplomacy;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * 数字工具类
 */
public abstract class NumberUtils {

    /**
     * itemId编码长度
     */
    private static final int ITEM_ID_LENGTH = 12;

    /**
     * 转Integer
     *
     * @param obj
     * @return
     */
    public static Integer getInteger(Object obj) {
        if (null == obj) {
            return null;
        }
        if (obj instanceof Long) {
            return ((Long) obj).intValue();
        } else {
            return (Integer) obj;
        }
    }

    /**
     * 转Integer
     *
     * @param obj
     * @return
     */
    public static Long getLong(Object obj) {
        if (null == obj) {
            return null;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        } else {
            return Long.valueOf(String.valueOf(obj));
        }
    }

    /**
     * String转Integer
     *
     * @param str
     * @return java.lang.Integer
     */
    public static Integer convertString2Integer(String str) {
        if (StringUtils.isEmpty(str)) {
            return 0;
        }
        Pattern pattern = compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return 0;
        }
        return Integer.valueOf(str);
    }

    /**
     * 判断编码是否是ITEM编码
     *
     * @param productId
     * @return java.lang.Boolean
     */
    public static Boolean isItem(String productId) {
        if (!StringUtils.isNumeric(productId)) {
            return false;
        }

        if (StringUtils.length(productId) != ITEM_ID_LENGTH) {
            return false;
        }

        try {
            Long.parseLong(productId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
